package com.creaminomedia.epictures;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.media.MediaScannerConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

@SuppressLint("NewApi")
public class SingleView extends Activity {
	static Context context;
	static String[] pictures;
	String baseUrl = "http://www.creamino-media.de/epictures/";
	static String baseUrlPics = "http://www.creamino-media.de/epictures/pics/";
	public static ImageView imageView;
	public static ProgressBar progress;
	static int piccount = 0;
	static ArrayList<Bitmap> pics = new ArrayList<Bitmap>();
	String[] sendchoices = new String[] {"SMS", "WhatsApp", "Facebook"};
	int selectedItem = -1;
	static int isRefreshing = 0;
	Menu menucopy;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_single_view);
		
		context = getApplicationContext();
		imageView = (ImageView)findViewById(R.id.imageView1);
		progress = (ProgressBar)findViewById(R.id.progress);
		
		if (Build.VERSION.SDK_INT >= 13) {
            ActionBar actionBar = getActionBar();
			actionBar.setIcon(R.drawable.logo);
			actionBar.setDisplayShowTitleEnabled(false);
        } 
		
		if(!haveNetworkConnection()) {
			new AlertDialog.Builder(this)
		    .setTitle("No internet connection")
		    .setMessage("Could not find any connection to the internet. Please fix it!")
		    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int which) { 
		            finish();
		            return;
		        }
		     })
		     .show();
		}
		
		/*boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

		if(isSDPresent){
		  System.out.println("SD card ist drin!!!");
		}
		else{
		  System.out.println("SD card is NICHT drin!!!");
		}*/
		
		getPictures();
		
		imageView.setOnTouchListener(new OnSwipeTouchListener() {
		    public void onSwipeRight() {
		    	if(piccount > 0 && isRefreshing == 0) {
		    		prevPicture();
		    	}
		    }
		    public void onSwipeLeft() {
		    	if(piccount < pictures.length - 1 && isRefreshing == 0) {
		    		nextPicture();
		    	}
		    }
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.single_view, menu);
		
		menucopy = menu;
		MenuItem item_save = menucopy.findItem(R.id.savepicture);
		
		if (Build.VERSION.SDK_INT < 13) {
            item_save.setIcon(null);
        } 
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
			switch (item.getItemId()) {
				case R.id.savepicture:
					SaveImage(0);
					return true;
				case R.id.sendpicture:
					sendDialog();
					return true;
				default:
					return super.onOptionsItemSelected(item);
			}
	}
	
	private void sendDialog() {
		AlertDialog.Builder builder = 
	              new AlertDialog.Builder(this);
	          builder.setTitle("Select how do you want to send");         
	          int selected = selectedItem;         
	          builder.setSingleChoiceItems(
	            sendchoices, 
	                  selected, 
	                  new DialogInterface.OnClickListener() {
	               
	              @Override
	              public void onClick(DialogInterface dialog, int which) {
	               selectedItem = which;
	                  dialog.dismiss();
	                  
	                  switch (selectedItem) {
	                  	case 0:
	                  		SendPictures.SMS();
	                  		return;
	                  	case 1:
	                  		SendPictures.WhatsApp();
	                  		return;
	                  	case 2:
	                  		SendPictures.FB();
	                  		return;
	                  }
	              }
	          });
	          AlertDialog alert = builder.create();
	          alert.show();
	}
	
	private void getPictures() {	
		AsyncHttp task2 = new AsyncHttp();
		task2.execute(baseUrl + "main.php");
	}
	
	private void nextPicture() {
		piccount += 1;
		if(pics.size() > piccount) {
			imageView.setImageBitmap(pics.get(piccount));
			return;
		}
		
		Bitmap bitmap = null;
		imageView.setImageBitmap(bitmap);
		
		ImageDownloader task = new ImageDownloader();
        task.execute(new String[] {baseUrlPics + pictures[piccount]});
	}
	
	private void prevPicture() {
		piccount -= 1;
		if(pics.size() > piccount) {
			imageView.setImageBitmap(pics.get(piccount));
			return;
		}
		
		Bitmap bitmap = null;
		imageView.setImageBitmap(bitmap);
		
		ImageDownloader task = new ImageDownloader();
        task.execute(new String[] {baseUrlPics + pictures[piccount]});
	}

	public static void SaveImage(int type){ 
		imageView.buildDrawingCache();
		Bitmap ImageToSave = imageView.getDrawingCache();
		
        String file_path = Environment.getExternalStorageDirectory()
      	      + File.separator + "Epictures";
        File dir = new File(file_path); 
          
        if(!dir.exists()){ 
            dir.mkdirs(); 
        } 
          
        File file = new File(dir, pictures[piccount]); 
          
        try { 
            FileOutputStream fOut = new FileOutputStream(file); 
            ImageToSave.compress(Bitmap.CompressFormat.JPEG, 85, fOut); 
            fOut.flush(); 
            fOut.close(); 
            MakeSureFileWasCreatedThenMakeAvabile(file); 
            if(type == 0) {
            	Toast.makeText(context, "Picture saved", Toast.LENGTH_SHORT).show();
            }
            imageView.destroyDrawingCache();
        }  
        catch (FileNotFoundException e) {Toast.makeText(context, "Picture save failed!", Toast.LENGTH_SHORT).show();} 
        catch (IOException e){Toast.makeText(context, "Picture save failed!", Toast.LENGTH_SHORT).show();}   
    } 
  
    private static void MakeSureFileWasCreatedThenMakeAvabile(File file) { 
        MediaScannerConnection.scanFile(context, 
                new String[] { file.toString() }, null, 
                new MediaScannerConnection.OnScanCompletedListener() { 
            public void onScanCompleted(String path, Uri uri) {                 
            } 
        }); 
          
    }       
	
	private boolean haveNetworkConnection() {
	    boolean haveConnectedWifi = false;
	    boolean haveConnectedMobile = false;

	    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
	    for (NetworkInfo ni : netInfo) {
	        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
	            if (ni.isConnected())
	                haveConnectedWifi = true;
	        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
	            if (ni.isConnected())
	                haveConnectedMobile = true;
	    }
	    return haveConnectedWifi || haveConnectedMobile;
	}

}
